package cn.harry.cabinet.theme.updater

import android.app.Activity
import android.content.Context
import android.content.res.ColorStateList
import android.graphics.Color
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.ImageButton
import android.widget.ImageView
import android.widget.TextView
import androidx.cardview.widget.CardView
import androidx.core.content.ContextCompat
import cn.harry.cabinet.R
import cn.harry.cabinet.theme.components.ThemePreviewComponent
import cn.harry.cabinet.theme.constants.ThemeConstants
import cn.harry.cabinet.theme.manager.ButtonThemeManager
import cn.harry.cabinet.theme.manager.ThemeManager

/**
 * 动态主题更新工具 - 重构版本
 * 用于在运行时更新界面元素的颜色，实现实时主题切换
 * 
 * 特性：
 * - 递归视图更新
 * - 智能组件识别
 * - 集成专业管理器
 * - 兼容性处理
 */
object DynamicThemeUpdater {
    
    /**
     * 递归更新ViewGroup中所有子视图的主题颜色
     */
    fun updateViewTheme(view: View, theme: ThemeManager.Theme, context: Context) {
        when (view) {
            is ViewGroup -> {
                // 递归更新所有子视图
                for (i in 0 until view.childCount) {
                    updateViewTheme(view.getChildAt(i), theme, context)
                }
                
                // 更新ViewGroup本身的背景
                updateViewGroupTheme(view, theme, context)
            }
            is TextView -> updateTextViewTheme(view, theme, context)
            is Button -> updateButtonTheme(view, theme, context)
            is ImageButton -> updateImageButtonTheme(view, theme, context)
            is ImageView -> updateImageViewTheme(view, theme, context)
            is CardView -> updateCardViewTheme(view, theme, context)
        }
    }
    
    /**
     * 更新Activity主题
     */
    fun updateActivityTheme(activity: Activity, theme: ThemeManager.Theme) {
        try {
            val rootView = activity.findViewById<View>(android.R.id.content)
            rootView?.let { 
                updateViewTheme(it, theme, activity)
            }

        } catch (e: Exception) {
            android.util.Log.w(ThemeConstants.LogTags.DYNAMIC_THEME_UPDATER, 
                "Activity theme update failed: ${e.message}")
        }
    }
    
    /**
     * 更新TextView主题
     */
    private fun updateTextViewTheme(textView: TextView, theme: ThemeManager.Theme, context: Context) {
        try {
            val themeColors = ThemeManager.getThemeColors(theme)
            
            // 根据当前文字颜色决定新的主题颜色
            val currentColor = textView.currentTextColor
            
            when {
                // 主要文字颜色
                isColorSimilar(currentColor, ContextCompat.getColor(context, R.color.tech_text_primary)) ||
                isColorSimilar(currentColor, Color.WHITE) -> {
                    textView.setTextColor(ContextCompat.getColor(context, themeColors.onSurface))
                }
                // 次要文字颜色
                isColorSimilar(currentColor, ContextCompat.getColor(context, R.color.tech_text_secondary)) -> {
                    textView.setTextColor(ContextCompat.getColor(context, themeColors.onSurfaceVariant))
                }
                // 强调色文字
                isColorSimilar(currentColor, ContextCompat.getColor(context, R.color.tech_text_accent)) ||
                isColorSimilar(currentColor, ContextCompat.getColor(context, R.color.tech_neon_blue)) -> {
                    textView.setTextColor(ContextCompat.getColor(context, themeColors.primary))
                }
            }
        } catch (e: Exception) {
            android.util.Log.d(ThemeConstants.LogTags.DYNAMIC_THEME_UPDATER, 
                "TextView theme update skipped: ${e.message}")
        }
    }
    
    /**
     * 更新Button主题
     */
    private fun updateButtonTheme(button: Button, theme: ThemeManager.Theme, context: Context) {
        try {
            // 使用ButtonThemeManager进行智能按钮主题更新
            ButtonThemeManager.applyButtonTheme(
                button = button,
                theme = theme,
                buttonType = detectButtonTypeFromContext(button, context),
                context = context
            )
        } catch (e: Exception) {
            android.util.Log.d(ThemeConstants.LogTags.DYNAMIC_THEME_UPDATER, 
                "Button theme update failed: ${e.message}")
        }
    }
    
    /**
     * 从上下文智能检测按钮类型
     */
    private fun detectButtonTypeFromContext(button: Button, @Suppress("UNUSED_PARAMETER") _context: Context): ButtonThemeManager.ButtonType {
        return when (button.id) {
            // 明确的主要按钮
            in ThemeConstants.ButtonIds.primaryButtonIds -> ButtonThemeManager.ButtonType.PRIMARY
            
            // 明确的次要按钮
            in ThemeConstants.ButtonIds.secondaryButtonIds -> ButtonThemeManager.ButtonType.SECONDARY
            
            // 根据按钮文字智能判断
            else -> {
                val text = button.text.toString().lowercase()
                when {
                    ThemeConstants.ButtonKeywords.primaryKeywords.any { text.contains(it) } -> 
                        ButtonThemeManager.ButtonType.PRIMARY
                    ThemeConstants.ButtonKeywords.secondaryKeywords.any { text.contains(it) } -> 
                        ButtonThemeManager.ButtonType.SECONDARY
                    else -> ButtonThemeManager.ButtonType.PRIMARY
                }
            }
        }
    }
    
    /**
     * 更新ImageButton主题
     */
    private fun updateImageButtonTheme(imageButton: ImageButton, theme: ThemeManager.Theme, context: Context) {
        try {
            // 使用ButtonThemeManager处理ImageButton
            ButtonThemeManager.applyImageButtonTheme(
                imageButton = imageButton,
                theme = theme,
                context = context
            )
        } catch (e: Exception) {
            android.util.Log.d(ThemeConstants.LogTags.DYNAMIC_THEME_UPDATER, 
                "ImageButton theme update failed: ${e.message}")
        }
    }
    
    /**
     * 更新ImageView主题
     */
    private fun updateImageViewTheme(imageView: ImageView, theme: ThemeManager.Theme, context: Context) {
        try {
            // 跳过ThemePreviewComponent内的ImageView，因为它们需要显示各自主题的固有颜色
            var parent = imageView.parent
            while (parent != null) {
                if (parent is ThemePreviewComponent) {
                    return
                }
                parent = parent.parent
            }
            
            val themeColors = ThemeManager.getThemeColors(theme)
            
            // 更新图标颜色（如果有tint）
            imageView.imageTintList?.let {
                imageView.imageTintList = ColorStateList.valueOf(ContextCompat.getColor(context, themeColors.primary))
            }
        } catch (e: Exception) {
            android.util.Log.d(ThemeConstants.LogTags.DYNAMIC_THEME_UPDATER, 
                "ImageView theme update skipped: ${e.message}")
        }
    }
    
    /**
     * 更新CardView主题
     */
    private fun updateCardViewTheme(cardView: CardView, theme: ThemeManager.Theme, context: Context) {
        try {
            val themeColors = ThemeManager.getThemeColors(theme)
            
            // 更新卡片背景色
            cardView.setCardBackgroundColor(ContextCompat.getColor(context, themeColors.surface))
        } catch (e: Exception) {
            android.util.Log.d(ThemeConstants.LogTags.DYNAMIC_THEME_UPDATER, 
                "CardView theme update skipped: ${e.message}")
        }
    }
    
    /**
     * 更新ViewGroup主题
     */
    private fun updateViewGroupTheme(viewGroup: ViewGroup, @Suppress("UNUSED_PARAMETER") _theme: ThemeManager.Theme, @Suppress("UNUSED_PARAMETER") _context: Context) {
        // 更新背景颜色（如果有设置背景色）
        viewGroup.background?.let {
            // 对于有背景的ViewGroup，可以考虑更新背景色
            // 这里可以根据需要进行更具体的处理
        }
    }
    
    /**
     * 判断两个颜色是否相似
     */
    private fun isColorSimilar(color1: Int, color2: Int, threshold: Int = 30): Boolean {
        val r1 = Color.red(color1)
        val g1 = Color.green(color1)
        val b1 = Color.blue(color1)
        
        val r2 = Color.red(color2)
        val g2 = Color.green(color2)
        val b2 = Color.blue(color2)
        
        return kotlin.math.abs(r1 - r2) <= threshold &&
               kotlin.math.abs(g1 - g2) <= threshold &&
               kotlin.math.abs(b1 - b2) <= threshold
    }
    
    /**
     * 批量更新指定类型的视图
     */
    fun updateViewsByType(
        rootView: View,
        theme: ThemeManager.Theme,
        viewType: Class<*>,
        context: Context
    ) {
        fun updateRecursively(view: View) {
            if (viewType.isInstance(view)) {
                updateViewTheme(view, theme, context)
            } else if (view is ViewGroup) {
                for (i in 0 until view.childCount) {
                    updateRecursively(view.getChildAt(i))
                }
            }
        }
        
        updateRecursively(rootView)
    }
    
    /**
     * 强制更新所有主题相关视图
     */
    fun forceUpdateAllViews(activity: Activity, theme: ThemeManager.Theme) {
        try {
            // 更新Activity主题
            updateActivityTheme(activity, theme)
            
            // 使用专门的管理器更新特定组件
            val rootView = activity.findViewById<View>(android.R.id.content)
            rootView?.let { 
                ButtonThemeManager.updateAllButtonsInView(it, theme, activity)
            }
        } catch (e: Exception) {
            android.util.Log.w(ThemeConstants.LogTags.DYNAMIC_THEME_UPDATER, 
                "Force update failed: ${e.message}")
        }
    }
}